<?php
/**
 * Created by PhpStorm.
 * User: krystal
 * Date: 2019/5/30
 * Time: 16:18
 */

namespace app\api\controller\v9;


use app\api\controller\v2\Auth;
use app\common\cachemodel\Orders as OrdersCacheModel;
use app\common\cachemodel\OrdersLib;
use app\common\cachemodel\OrdersLib as OrdersLibCacheModel;
use app\common\cachemodel\ZhunleUserAccountRecord;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\common\model\Orders as OrdersModel;
use app\common\service\ApplePay;
use Exception;
use think\Db;
use think\Log;

/**
 *  * 苹果支付结果验证
 * Class AppPayVerify
 * 官方@document https://developer.apple.com/documentation/technologies
 * 回调@document  https://developer.apple.com/documentation/appstorereceipts
 * @package app\api\controller\v9
 */
class AppPayVerify extends Auth
{
    /**
     * @return \think\response\Json
     * @throws ApiException
     * @throws Exception
     */
    public function index()
    {
        $param['ticket'] = input('ticket/s', '');
        $param['order_id'] = input('order_id', '');

        Log::write('苹果支付请求参数：' . var_export($param, true), 'apple_pay', true);

        if (Util::CheckAppVersion('2.9.9') === '大')
        {
            $res = ApplePay::verificationTicket($this->apple_pay_sandbox_model, $param['ticket'], ApplePay::$ticketPassword);
        } else
        {
            $res = ApplePay::verificationTicket($this->apple_pay_sandbox_model, $param['ticket']);
        }

        if ($res['status'] !== 0 || empty($res['receipt']['in_app']) || $res['receipt']['bundle_id'] !== 'com.liuhe.xzns')
        {
            return show(config('code.success'), '请求失败');
        }

        $column = array_column($res['receipt']['in_app'], 'purchase_date_ms');
        array_multisort($column, SORT_NUMERIC, SORT_DESC, $res['receipt']['in_app']);// 得到按 支付时间 排序
//        if ($res['receipt']['in_app'][0]['in_app_ownership_type'] !== 'PURCHASED')
//        {
//            return show(config('code.success'), '请求失败');
//        }
        $transactionId = $res['receipt']['in_app'][0]['transaction_id'];//苹果交易ID
        $productId = $res['receipt']['in_app'][0]['product_id'];//商品ID
        $purchaseDateMs = $res['receipt']['in_app'][0]['purchase_date_ms'];//支付时间
        $gid = str_replace('apple_pay_', '', $productId);

        $num = OrdersLibCacheModel::getOrderAccountType($param['order_id'])['num'];
        //准币处理
        if ($num === 7)
        {
            try
            {
                $tmp = (new ZhunleUserAccountRecord())->where('transaction_id', $transactionId)->field('id')->find();
                if ($tmp)
                {
                    return show(config('code.success'), '');
                }
                $orders = (new ZhunleUserAccountRecord())->where(['order_id' => $param['order_id']])->field('uid,order_type,total_amount,gid,status')->findOrFail()->toArray();
                if ($orders['uid'] != $this->user['id'] || $orders['status'] || $orders['gid'] != $gid)
                {
                    return show(config('code.error'), '订单不存在');
                }
                //票据标记
                OrdersLibCacheModel::UpdateCoin($param['order_id'], $orders['order_type'], $orders['total_amount'], $orders['uid'], 1, 9, $transactionId);
            }
            catch (\Exception $e)
            {
                return show(config('code.error'), '订单不存在');
            }
        } else//VIP处理
        {
            // 生成订单到数据库
            $OrdersCacheModel = new OrdersCacheModel();
            $OrdersModel = new OrdersModel();
            $tmp = $OrdersModel->where('transaction_id', $transactionId)->field('id')->find();
            if ($tmp)
            {
                return show(config('code.success'), '票据已被使用');
            }
            $orders = $OrdersCacheModel->getInfoById($param['order_id']);
            if (!$orders || $orders['uid'] != $this->user['id'])
            {
                return show(config('code.error'), '订单不存在');
            }
            $orders['order_type'] = (int)$orders['order_type'];
            if (in_array($orders['order_type'], [3, 4, 7], true))
            {
                (new \app\common\service\Orders())->notify_handle($param['order_id'], $orders['total_amount'], 9, $transactionId);
            } elseif ($orders['order_type'] === 8)
            {
                Db::startTrans();
                try
                {
                    $extend = $orders['extend'] ? json_decode($orders['extend'], true) : [];
                    $UserVip = OrdersLib::getUserVipTime($this->user['id'], $gid);//返回时间为时间戳
                    $extend['vip_start_time'] = $UserVip['vip_start_time'];
                    $extend['vip_end_time'] = $UserVip['vip_end_time'];
                    //更新订单2.0缓存
                    $OrdersCacheModel->UpdateData($param['order_id'], ['status' => 4, 'transaction_id' => $transactionId, 'extend' => json_encode($extend, true), 'pay_time' => $this->request->time()], 4);
                    // 删除旧订单缓存
                    $OrdersModel->rm_cache(['oid' => $orders['id'], 'del_add' => 0, 'order_id' => $param['order_id'], 'uid' => $this->user['id'], 'gid' => $orders['gid']]);
                    $OrdersCacheModel->SaveTotalPrepaidOrder($orders['order_type'], 0);
                    Db::commit();
                }
                catch (Exception $e)
                {
                    Db::rollback();
                    Log::write('订单入库失败：' . $e->getMessage() . '【' . $e->getFile() . $e->getLine() . '】', 'error');
                }
                //vip更新状态和星力值
                OrdersLibCacheModel::UpdateVipStatus($orders, $orders['gid']);
            }

        }
        ApplePay::verificationTicket($this->apple_pay_sandbox_model, $param['ticket'], ApplePay::$ticketPassword, true);
        return show(config('code.success'), '请求成功');
    }
}
